<template>
  <MenuPage
    :data="systemList"
    :columns="systemCol"
    :page.sync="queryParams.pageIndex"
    :size.sync="queryParams.pageSize"
    :total="systemTotal"
    :loading="systemListLoading"
    @queryFun="getNewData">
    <template slot="search">
      <Button type="primary" ghost class="md-add-jh" @click="showModal(null)">创建{{pageBtnTxt}}</Button>
      <Divider type="vertical" style="margin: 10px 0px 10px 10px;" />
      <Select filterable clearable v-model="queryParams.natureCode" @on-change="changePage(1)" placeholder="选择单位性质" style="margin-left: 15px;width: 150px">
        <Option v-for="unit in natureOptions" :key="unit.dictid" :value="unit.dictid">{{unit.dictname}}</Option>
      </Select>
      <Input v-model.trim="queryParams.name"  clearable placeholder="请输入名称或地址" @on-change="changePage(1)" style="width: 180px;margin-left: 15px" />
      <Input v-model.trim="queryParams.liaison"  clearable placeholder="请输入联系人或联系手机" @on-change="changePage(1)" style="width: 180px;margin-left: 15px" />
      <Button class="header-btn" type="primary" ghost style="height: 32px;margin-left: 5px;" @click="refreshSystemList()">
        <i class="el-icon-refresh-right" />
      </Button>
    </template>
    <Modal
        v-model="modalData.show"
        :title="`${isAdd ? '创建' : '修改'}单位`"
        @on-visible-change="changeVisible"
        class="my-modal">
      <Form
          ref="formInline"
          :label-width="140"
          :model="formInline"
          :rules="ruleInline">
        <FormItem prop="name" label="单位名称">
          <Input clearable v-model="formInline.name"></Input>
        </FormItem>
        <FormItem prop="address"  label="单位地址">
          <Input clearable v-model="formInline.address"></Input>
        </FormItem>
        <FormItem prop="natureCode"  label="单位性质">
          <Select filterable transfer filterable clearable v-model="formInline.natureCode" placeholder="">
            <Option :value="item.dictid" v-for="item in natureOptions" :key="item.dictid">{{ item.dictname }}</Option>
          </Select>
        </FormItem>
        <FormItem prop="code"  label="统一社会信用代码">
          <Input clearable v-model="formInline.code"></Input>
        </FormItem>
        <FormItem prop="site"  label="官网">
          <Input clearable v-model="formInline.site"></Input>
        </FormItem>
        <FormItem prop="liaison"  label="联系人">
          <Input clearable v-model="formInline.liaison"></Input>
        </FormItem>
        <FormItem prop="tel"  label="联系电话">
          <Input clearable v-model="formInline.tel"></Input>
        </FormItem>
        <FormItem prop="phone"  label="联系人手机">
          <Input clearable v-model="formInline.phone"></Input>
        </FormItem>
        <FormItem label="logo" prop="logo">
          <itemUpload ref="logoUpload"  @upload-success="uploadSuccess" :formatArr="['jpg','png','jpeg']"
                      :showUploadList="true" uploadText="上传图片"  @clearFile="setClear"
                      fileType="images"></itemUpload>
        </FormItem>
      </Form>
      <div slot="footer" class="footer">
        <Button @click="modalData.show = false">取消</Button>
        <Button @click="saveAssetUnit" :loading="modalData.loading" type="primary">确定</Button>
      </div>
    </Modal>
    <Modal
      v-model="modalDataDetail.show"
      :title="`${pageBtnTxt}详情`"
      footer-hide
      class="my-modal">
      <div class="item-table">
        <p>
          <span class='label'>单位名称</span>
          <span>{{ detailInfo.name }}</span>
        </p>
        <p>
          <span class='label'>单位地址</span>
          <span>{{ detailInfo.address }}</span>
        </p>
        <p>
          <span class='label'>单位性质</span>
          <span>{{ detailInfo.natureName }}</span>
        </p>
        <p>
          <span class='label'>统一社会信用代码</span>
          <span>{{ detailInfo.code }}</span>
        </p>
        <p>
          <span class='label'>官网</span>
          <span>{{ detailInfo.site }}</span>
        </p>
        <p>
          <span class='label'>联系人</span>
          <span>{{ detailInfo.liaison }}</span>
        </p>
        <p>
          <span class='label'>联系电话</span>
          <span>{{ detailInfo.tel }}</span>
        </p>
        <p>
          <span class='label'>联系人手机</span>
          <span>{{ detailInfo.phone }}</span>
        </p>
        <p>
          <span class='label'>logo</span>
          <span>
                        <img :src="`/Learn${detailInfo.logo}`" style="width: auto; height: 40px; vertical-align: middle;" v-if="detailInfo.logo">
                        <span v-else></span>
                        </span>
        </p>
      </div>
  </Modal>
  </MenuPage>
</template>
<script>

import encryption from '@/libs/encryption.js'
import * as paramsConfig from '../paramsConfig'
import urlList from './detail/urlList'
import itemUpload from '../components/item-upload/index.vue'
import drawers from '../components/drawers.vue'
import edit from './addFatoryModal.vue'
import relativeSystem from './detail/relativeSystem.vue'
import pageTitle from '@/mixin/pageTitle';
import { getUnitNatureCodeList} from "./logic/assetLogic";
import {
  addProductOwnership,
  deleteProductOwnership,
  queryProductOwnershipList,
  updateProductOwnership
} from "./api/productOwnership";
import { validateTelephone, validateName, validatePhoneNotRequired} from "../../../libs/reg";
import {assetUnitCol} from "./configData/assetUnitCol";
export default {
  components: {itemUpload,drawers,urlList,relativeSystem,edit},
  mixins:[pageTitle],
  data () {
    return {
      natureOptions:[],
      productInfo:{},
      currentInfo:{},
      deployModal:false,
      systemDeployRecordList:[],
      systemDeployRecordTotal:0,
      systemDeployRecordLoading:false,
      systemDeployRecordCol:[
        {title:'部件名称',key:'productPartName'},
        {title:'IP资产',key:'ip'},
        {title:'端口',key:'port'},
        {title:'网络区域',key:'assetNetworkMeshName'},
        {title:'网络名称',key:'testNetinfoName'}
      ],

      assetCategoryList:[],
      unitList:[],
      vendorList:[],

      stateOptions:paramsConfig.SYSTEM_STATE_OPTIONS,

      systemList:[],

      institutionList:[],
      industryList:[],
      netMeshList:[],
      netInfoList:[],

      systemListLoading:false,
      systemTotal:0,

      formInline: {},
      ruleInline: {
        name: [
          { required: true, message: `单位名称不能为空`, trigger: 'blur,change' },
          { type:'string',max: 64,trigger:'blur,change',message:'最多输入64个字符' },
          { validator:validateName, trigger: 'blur,change' }
        ],
        address: [
          { required: true, message: `单位地址不能为空`, trigger: 'blur,change' },
          { type:'string',max: 200,trigger:'blur,change',message:'最多输入200个字符' },
        ],
        natureCode: [
          { required: true, message: `单位性质不能为空`, trigger: 'blur,change' },
          { type:'string',max: 200,trigger:'blur,change',message:'最多输入200个字符' },
        ],
        tel: [
          { validator: validateTelephone, trigger: 'blur,change' }
        ],
        phone: [
          { validator: validatePhoneNotRequired, trigger: 'blur,change' }
        ]
      },
      modalData: {
        show: false,
        loading: false
      },
      modalDataDetail:{
        show:false
      },
      isAdd: false,
      upgradeType: 'add',
      typeOptions: ['软件', '硬件'],
      isUpgrade: false,
      file: {},
      optionList: [],
      detailInfo: {},
      queryParams:{
        pageIndex:1,
        pageSize:10
      },
      // 用户信息
      USER_ID: '',
      isRootDesinger: '',
      distributed: false,
      // 镜像列表
      assetListLoading: false,
      assetCategory: [],
      unit: '',
      industry: '',
      systemCol:[],
      actionButtons: [
        {
          txt: '详情',
          fun: (obj) => {
            this.modalDataDetail.show = true
            this.detailInfo = obj
          }
        },
        {
          txt: '修改',
          fun:(obj)=>{
            this.showModal(obj)
          },
        },
        {
          txt: '删除',
          tooltip: true,
          type: 'delete',
          title: '确定要删除吗？',
          fun:this.delItem
        }
      ],
      searchImageName: '',
      assetModelInput: '',
      creatByMeModal: false,
      // 创建和修改镜像
      imageID: '',
      assetModal: false,
      updateUrl: `/api/resource-manager/image/add`,
      addAssetBtnLoading: false,
      productTypeIds:[],
      setDisabled: false,
      isCreate: true,
      //profile
      profileList: [],
      // 镜像用户
      showImgUser: false,
      formIsShow: false,
      imageUserId: '',
      addUserLoading: false,
      createPort: '22',
      isCreatUser: false,
      isClound: false,
      flag: 0, //标记成功的次数
      filedArr: [],//承装切片的容器
      oldTime: 0,//初始化时间
      progressflag: false,//控制进度条的展示
      fileName: '',
      saveTargetStatusArr: [],//存储中间状态
      messageSwitch: false,//解决鼠标移入失败或者成功验证状态气泡框位置错乱设置的开关
      systemVersion:[]
    }
  },
  computed: {
    showProductName(){
      return ``
    }
  },
  watch: {


  },
  created () {
    // 获取用户id
    let November = sessionStorage.getItem('November')
    November = JSON.parse(encryption.SelfUseDecrypt(November))
    this.USER_ID = November.userId
    this.isRootDesinger = November.isRootDesinger
    this.distributed = November.distributed
    // this.distributedRange = this.$store.state.user.distributedRange
  },
  mounted () {
    getUnitNatureCodeList(this,'natureOptions')
    this.systemCol = assetUnitCol(this);
    let getPage = this.$route.query.page ? parseInt(this.$route.query.page) : 1
    this.queryParams.pageIndex = getPage
    this.getNewData()
  },
  methods: {
    handleOk(type){
      if(type === 'add'){
        this.queryParams.pageIndex = 1;
      }
      this.getNewData()
    },
    getNewData(){
      queryProductOwnershipList(this.queryParams).then(res=>{
        if(res.code==1){
          this.systemList = res.data.items;
          this.systemTotal = res.data.total;
        }else{
          this.$Message.error(res.message)
        }

      }).finally(()=>{

      })
    },
    // 隐藏模态框时，重置表单数据
    changeVisible(type) {
      if (!type) {
        this.$refs.formInline.resetFields()
        this.modalData.loading = false
      }
    },
    // 创建、修改单位
    saveAssetUnit() {
      this.$refs.formInline.validate(valid => {
        if (valid) {
          this.modalData.loading = true
          let apiName = this.isAdd ? addProductOwnership : updateProductOwnership
          let data = Object.assign({}, this.formInline)
          if (this.isAdd) { // 创建操作确认把id删掉，避免造成错误
            delete data.id
          }
          data.natureName = (this.natureOptions.find(item => item.dictid === data.natureCode) || {}).dictname
          apiName(data).then(({ code, message }) => {
            if (code !== 1) {
              this.$Message.warning(message)
              return
            }
            // 创建、改修成功
            this.$Message.success(`${this.isAdd ? '创建' : '修改'}单位成功`)
            this.getNewData()
            this.modalData.show = false
          }).catch(() => {
            this.$Message.error(`${this.isAdd ? '创建' : '修改'}单位异常`)
          }).finally(() => {
            this.modalData.loading = false
          })
        }
      })
    },
    changePage(page){
      this.queryParams.pageIndex = page;
      this.getNewData();
    },
    delItem(params){
      deleteProductOwnership(params.id).then(res=>{
        if(res.code==1){
          this.$Message.info('删除成功!');
           // 删除后展示当前页，当前页没有数据展示前一页
           let page = (this.systemList.length == 1 && this.queryParams.pageIndex > 1) ?
           this.queryParams.pageIndex - 1 : this.queryParams.pageIndex;
           this.$set(this.queryParams,'pageIndex',page);
          this.getNewData()
        }else{
          this.$Message.error(res.message);
        }
      })
    },
    refreshSystemList(){
      this.queryParams = {
        pageIndex:1,
        pageSize:10,
      }
      this.getNewData()
    },
    // 上传logo成功，设置logo
    uploadSuccess(val){
      this.formInline.logo = val.filePath
    },
    // 清除logo
    setClear(){
      this.formInline.logo = ''
    },
    // 下载文件
    downloadFile(item) {
      if (!item.fileId) {
        return
      }
      let a = document.createElement('a');
      let fileName = item.fileName; //filename名称截取
      a.href = `/api/minio/download/${item.fileId}`;
      a.download = fileName; //命名下载名称
      a.click(); //点击触发下载
    },
    // 打开模态框
    showModal(data) {
      this.modalData.show = true;
      this.isAdd = !data
      this.formInline = Object.assign({}, data || {
        name: '',
        address: '',
        natureCode: '',
        code: '',
        site: '',
        liaison: '',
        tel: '',
        phone: '',
        logo: ''
      })
      this.formInline.logo?this.$refs.logoUpload.showDefaultList({filePath:this.formInline.logo}): this.$refs.logoUpload.showDefaultList(null);
    }
  },
  beforeDestroy () {

  }
}
</script>
<style scoped>
.my-form-item /deep/ .ivu-form-item-content{
  display: flex;
}
 .item-table {
   display: table;
   width: 100%;
   border: 1px solid var(--table-border);
   table-layout: fixed;
   word-break: break-all;
 }
.item-table p {
  display: table-row;
  line-height: 36px;
  text-align: center;
}
.item-table p span {
  display: table-cell;
  border-bottom: 1px solid var(--table-border);
}
.ios-alert {
  /* position: absolute;
        top: -44px;
        right: -404px; */
  color: orange;
  font-size: 16px;
  cursor: pointer;
}
.too {
  position: absolute;
  left: 113px;
  top: -1px;
}
</style>


